package com.iplay.实战java高并发程序设计.chapter3.c34;

import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author dangwu
 * @since 2021/11/3 10:37 上午
 */
@State(Scope.Benchmark)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@BenchmarkMode(Mode.Throughput)
public class MapTest {
    static Map hashMap = new HashMap();
    static Map syncHashMap = Collections.synchronizedMap(new HashMap<>());
    static Map concurrentHashMap = new ConcurrentHashMap();

    @Setup
    public void setup(){
        for (int i = 0; i < 100000; i++) {
            hashMap.put(Integer.toString(i),Integer.toString(i));
            syncHashMap.put(Integer.toString(i),Integer.toString(i));
            concurrentHashMap.put(Integer.toString(i),Integer.toString(i));
        }
    }


    @Benchmark
    public void hashMapGet(){
        hashMap.get(4);
    }
    @Benchmark
    public void syncHashMapGet(){
        syncHashMap.get(4);
    }
    @Benchmark
    public void concurrentHashMapGet(){
        concurrentHashMap.get(4);
    }
    @Benchmark
    public void hashMapSize(){
        hashMap.size();
    }
    @Benchmark
    public void syncHashMapSize(){
        syncHashMap.size();
    }
    @Benchmark
    public void concurrentHashMapSize(){
        concurrentHashMap.size();
    }

    /**
     * 一个线程
     * Benchmark                       Mode  Cnt        Score       Error   Units
     * MapTest.concurrentHashMapGet   thrpt   20   535288.160 ± 10001.011  ops/ms
     * MapTest.concurrentHashMapSize  thrpt   20   909590.489 ± 11271.894  ops/ms
     * MapTest.hashMapGet             thrpt   20   501724.773 ± 12259.599  ops/ms
     * MapTest.hashMapSize            thrpt   20  1475426.079 ± 28387.926  ops/ms
     * MapTest.syncHashMapGet         thrpt   20   200143.579 ±  5053.094  ops/ms
     * MapTest.syncHashMapSize        thrpt   20   349115.541 ±  7279.288  ops/ms
     * @param args
     * @throws RunnerException
     */

    public static void main(String[] args) throws RunnerException {
        Options build = new OptionsBuilder().include(MapTest.class.getSimpleName()).forks(2).build();
        new Runner(build).run();
    }
}
